﻿using System;
using System.Data;
using System.Configuration;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Text;

namespace WebApplication1
{

    public class ZenAPI
    {


        private static string _Username = "ddjjrrmm@hotmail.com";
        private static string _Password = "19861008";


        public ZenAPI()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static DataTable Load_Users()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://qcl.zendesk.com/users.xml");
            request.Method = "GET";
            request.Credentials = new NetworkCredential(_Username, _Password);
            request.ContentLength = 0;
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            string tmp = reader.ReadToEnd();
            StringReader stream = new StringReader(tmp);
            DataSet ds = new DataSet();
            ds.ReadXml(stream);
            DataTable dt = ds.Tables["user"];
            return dt;
        }

        public static void DeleteUser(string _ID)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://qcl.zendesk.com/users/" + _ID + ".xml");
                request.Method = "DELETE";
                request.Credentials = new NetworkCredential(_Username, _Password);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void CreateUser(string _IUserXml)
        {
            try
            {
                string strXML = _IUserXml; //"<user><email>drrrn@yourcompany.dk</email><name>Niraj</name><roles>4</roles><restriction-id>1</restriction-id></user>";
                byte[] bytes = Encoding.UTF8.GetBytes(strXML);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://zlbeyondstudy.zendesk.com/users.xml");
                request.Method = "POST";
                request.Credentials = new NetworkCredential(_Username, _Password);
                request.ContentType = "application/xml";
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static void UpdateUser(string _IUserXml, string _UserID)
        {
            try
            {
                string strXML = _IUserXml; //"<user><email>drrrn@yourcompany.dk</email><name>Niraj</name><roles>4</roles><restriction-id>1</restriction-id></user>";
                byte[] bytes = Encoding.UTF8.GetBytes(strXML);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://qcl.zendesk.com/users/" + _UserID + ".xml");
                request.Method = "PUT";
                request.Credentials = new NetworkCredential(_Username, _Password);
                request.ContentType = "application/xml";
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static DataTable Users(string _useID)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://qcl.zendesk.com/users/" + _useID + ".xml");
            request.Method = "GET";
            request.Credentials = new NetworkCredential(_Username, _Password);
            request.ContentLength = 0;
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            string tmp = reader.ReadToEnd();
            StringReader stream = new StringReader(tmp);
            DataSet ds = new DataSet();
            ds.ReadXml(stream);
            DataTable dt = ds.Tables["user"];
            return dt;
        }


        public static string GetTickets()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://zlbeyondstudy.zendesk.com/api/v1/requests.json");
            request.Method = "GET";
            request.Credentials = new NetworkCredential(_Username, _Password);
            request.ContentLength = 0;
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            string tmp = reader.ReadToEnd();
            StringReader stream = new StringReader(tmp);
            //DataSet ds = new DataSet();
            //ds.ReadXml(stream);
            //DataTable dt = ds.Tables["ticket"];
            return tmp;
        }

        public static DataTable GetTicket(string _TicketID)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://zlbeyondstudy.zendesk.com/api/v1/tickets/" + _TicketID + ".xml");
            request.Method = "GET";
            request.Credentials = new NetworkCredential(_Username, _Password);
            request.ContentLength = 0;
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            string tmp = reader.ReadToEnd();
            StringReader stream = new StringReader(tmp);
            DataSet ds = new DataSet();
            ds.ReadXml(stream);
            DataTable dt = ds.Tables["ticket"];
            return dt;
        }


        public static string PostTicket(String strXML)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(strXML);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://thebeyondstudy.zendesk.com/api/v1/tickets.xml");
            request.Method = "POST";
            request.Credentials = new NetworkCredential(_Username, _Password);
            request.ContentType = "application/xml";
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //Stream Answer = response.GetResponseStream();
            //StreamReader _Answer = new StreamReader(Answer);
            //return _Answer.ReadToEnd().ToString();  
            return response.Headers.ToString();
        }


        public static void DeleteTicket(string _ID)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://qcl.zendesk.com/tickets/" + _ID + ".xml");
                request.Method = "DELETE";
                request.Credentials = new NetworkCredential(_Username, _Password);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void UpdateTicket(String strXML, string _ID)
        {
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(strXML);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://zlbeyondstudy.zendesk.com/api/v1/tickets/" + _ID + ".xml");
                request.Method = "PUT";
                request.Credentials = new NetworkCredential(_Username, _Password);
                request.ContentType = "application/xml";
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void PostTicketcomment(String strXML, string _ID)
        {
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(strXML);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://zlbeyondstudy.zendesk.com/api/v1/tickets/" + _ID + ".xml");
                request.Method = "PUT";
                request.Credentials = new NetworkCredential(_Username, _Password);
                request.ContentType = "application/xml";
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string PostAttachment(string fileToUpload)
        {
            FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
            string[] filename_=fileToUpload.Split('\\');
            int l = filename_.Length;
            string filename = filename_[l-1];
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://thebeyondstudy.zendesk.com/api/v1/uploads.json?filename="+filename);
            req.Method = "POST"; // you might use "POST"
            req.Credentials = new NetworkCredential(_Username, _Password);
            //req.ContentType = "application/xml";
            req.ContentLength = rdr.Length;
            req.AllowWriteStreamBuffering = true;
            Stream reqStream = req.GetRequestStream();
            byte[] inData = new byte[rdr.Length];
            // Get data from upload file to inData
            int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);
            // put data into request stream
            reqStream.Write(inData, 0, (int)rdr.Length);
            rdr.Close();
            reqStream.Close();
            HttpWebResponse response = (HttpWebResponse) req.GetResponse();
            Stream Answer = response.GetResponseStream();
            StreamReader reader = new StreamReader(Answer);
            string token = reader.ReadToEnd();
            return token.Substring(10,15);
            //return response.Headers.ToString();
        }

        public static string PostAttachmentWithToken(string fileToUpload, string thetoken)
        {
            FileStream rdr = new FileStream(fileToUpload, FileMode.Open);
            string[] filename_ = fileToUpload.Split('\\');
            int l = filename_.Length;
            string filename = filename_[l - 1];
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://thebeyondstudy.zendesk.com/api/v1/uploads.json?filename=" + filename + "&token=" + thetoken);
            req.Method = "POST"; // you might use "POST"
            req.Credentials = new NetworkCredential(_Username, _Password);
            //req.ContentType = "application/xml";
            req.ContentLength = rdr.Length;
            req.AllowWriteStreamBuffering = true;
            Stream reqStream = req.GetRequestStream();
            byte[] inData = new byte[rdr.Length];
            // Get data from upload file to inData
            int bytesRead = rdr.Read(inData, 0, (int)rdr.Length);
            // put data into request stream
            reqStream.Write(inData, 0, (int)rdr.Length);
            rdr.Close();
            reqStream.Close();
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            Stream Answer = response.GetResponseStream();
            StreamReader reader = new StreamReader(Answer);
            string token = reader.ReadToEnd();
            return token.Substring(10, 15);
            //return response.Headers.ToString();
        }
    }
}